package com.xzt.bookstore.controller;

import com.xzt.bookstore.common.Result;
import com.xzt.bookstore.dto.OrderCreateRequest;
import com.xzt.bookstore.dto.OrderDTO;
import com.xzt.bookstore.service.OrderService;
import com.xzt.bookstore.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {
    
    private final OrderService orderService;
    private final JwtUtil jwtUtil;
    
    /**
     * 从请求头中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            return jwtUtil.getUserIdFromToken(token);
        }
        throw new RuntimeException("未登录");
    }
    
    /**
     * 从购物车创建订单
     */
    @PostMapping
    public Result<OrderDTO> createOrder(@Valid @RequestBody OrderCreateRequest request, HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            OrderDTO order = orderService.createOrderFromCart(userId, request);
            return Result.success("订单创建成功", order);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("创建订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户的订单列表
     */
    @GetMapping
    public Result<List<OrderDTO>> getUserOrders(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            List<OrderDTO> orders = orderService.getUserOrders(userId);
            return Result.success(orders);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单ID获取订单详情
     */
    @GetMapping("/{orderId}")
    public Result<OrderDTO> getOrderById(@PathVariable Long orderId, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            OrderDTO order = orderService.getOrderById(userId, orderId);
            return Result.success(order);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取订单详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 取消订单
     */
    @PutMapping("/{orderId}/cancel")
    public Result<String> cancelOrder(@PathVariable Long orderId, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            orderService.cancelOrder(userId, orderId);
            return Result.success("订单已取消");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("取消订单失败：" + e.getMessage());
        }
    }
}

